package cn.iocoder.yudao.module.happycore.service;

import cn.iocoder.yudao.module.happycore.controller.admin.oxproject.vo.PredictResponse;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.List;

@Service
public class PythonPredictService {

    private static final String PYTHON_API_URL = "http://127.0.0.1:8000/predict";

    /**
     * 调用 FastAPI /predict 接口进行预测
     *
     * @param modelPath 模型文件路径，例如 "models/svm_model_93.pkl"
     * @param classList 类别列表，例如 ["golden_retriever", "poodle", "husky"]
     * @param imageUrl  图片 URL 地址
     * @return 预测结果
     */
    public PredictResponse predictDogBreed(String modelPath, List<String> classList, String imageUrl) {
        RestTemplate restTemplate = new RestTemplate();
        classList.sort(
                String::compareToIgnoreCase
        );
        try {
            // 1️⃣ 下载图片到临时文件
            File tempFile = File.createTempFile("predict_", ".jpg");
            try (InputStream in = new URL(imageUrl).openStream()) {
                Files.copy(in, tempFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }

            // 2️⃣ 构造 JSON 参数
            String jsonBody = String.format(
                    "{\"model_path\": \"%s\", \"class_list\": [\"%s\"]}",
                    modelPath,
                    String.join("\",\"", classList)
            );


            // 3️⃣ 构造 multipart/form-data 请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new FileSystemResource(tempFile));
            body.add("json", jsonBody);

            // 4️⃣ 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 5️⃣ 调用 FastAPI 接口
            ResponseEntity<PredictResponse> response = restTemplate.exchange(
                    PYTHON_API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    PredictResponse.class
            );

            // 6️⃣ 删除临时文件
            tempFile.delete();

            // 7️⃣ 返回结果
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return response.getBody();
            } else {
                PredictResponse error = new PredictResponse();
                error.setStatus("error");
                error.setMessage("FastAPI 返回空结果或状态异常");
                return error;
            }

        } catch (Exception e) {
            e.printStackTrace();
            PredictResponse error = new PredictResponse();
            error.setStatus("error");
            error.setMessage("调用 FastAPI 出错: " + e.getMessage());
            return error;
        }
    }
}
